﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Transactions;

public partial class Main_ServiceInvoice_DebitNoteEdit : System.Web.UI.Page
{
    Datautility DU = new Datautility();
    List<string> ControlCounter;
    List<string> ddlServiceID;
    List<string> txtAdditionalID;
    List<string> txtAmountID;
    List<string> txtPECessID;
    List<string> txtHECessID;
    List<string> hidChkTaxableID;
    List<string> hiddebitnotechildID;

    int rowcount = 1;
    string strsql = string.Empty;

    protected override void LoadViewState(object savedState)
    {
        base.LoadViewState(savedState);
        OverrideRow();
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        string tranid = Request.QueryString["tranid"].ToString();
        string debitnoteid = Request.QueryString["debitnoteid"].ToString();

        if (!IsPostBack)
        {
            ControlCounter = new List<string>();
            ViewState["ControlCounter"] = ControlCounter;

            ddlServiceID = new List<string>();
            ViewState["ddlServiceID"] = ddlServiceID;

            txtAdditionalID = new List<string>();
            ViewState["txtAdditionalID"] = txtAdditionalID;

            txtAmountID = new List<string>();
            ViewState["txtAmountID"] = txtAmountID;

            txtPECessID = new List<string>();
            ViewState["txtPECessID"] = txtPECessID;

            txtHECessID = new List<string>();
            ViewState["txtHECessID"] = txtHECessID;

            hidChkTaxableID = new List<string>();
            ViewState["hidChkTaxableID"] = hidChkTaxableID;

            hiddebitnotechildID = new List<string>();
            ViewState["hiddebitnotechildID"] = hiddebitnotechildID;

            ViewState["rbtDebitNoteTypeValue"] = "0";

              fillBillFormat();
              fillCustomerName();
              fillService(ddlService1);
             CheckRef();
            lblAmount.Text = "Amount";
            lblHECess.Visible = false;
            txtHECess1.Visible = false;
            lblPECess.Visible = false;
            txtPECess1.Visible = false;
            txtServiceTaxPer.Visible = false;
            txtPECessPer.Visible = false;
            txtHECessPer.Visible = false;
            lblServiceTax.Text = "Service Tax %";
            txtServiceTaxPer.Visible = true;
            lblPECess1.Text = "P.E.Cess %";
            txtPECessPer.Visible = true;
            lblHECess1.Text = "H.E.Cess %";
            txtHECessPer.Visible = true;
            txtDate.Text = string.Format("{0:dd/MM/yyyy}", Convert.ToDateTime(System.DateTime.Now));
            if (txtDate.Text != "")
            {
              fillServicePEHETax(txtDate.Text);
            }
            bindmain();
        }
    }

    #region /*Function */
    protected void CheckRef()
    {
        SqlParameter[] sparam ={
                                   new SqlParameter("@FORMATID",ddlBillFormat.SelectedValue)
                               };
        DataTable DTFormatDetails = DU.getdatausingprocedure("USP_IVC_GetTransactionFormat", sparam);
        if (DTFormatDetails.Rows.Count > 0)
        {
            if (Convert.ToInt32(DTFormatDetails.Rows[0]["NARRATION"]) == 1)
            {
                txtNarration.Enabled = true;
            }
            else
            {
                txtNarration.Enabled = false;
            }
            if (Convert.ToInt32(DTFormatDetails.Rows[0]["REMARKS"]) == 1)
            {
                txtRemarks.Enabled = true;
            }
            else
            {
                txtRemarks.Enabled = false;
            }
            if (Convert.ToInt32(DTFormatDetails.Rows[0]["PREPAREDBY"]) == 1)
            {
                txtPreparedBy.Enabled = true;
            }
            else
            {
                txtPreparedBy.Enabled = false;
            }
            if (Convert.ToInt32(DTFormatDetails.Rows[0]["CHECKEDBY"]) == 1)
            {
                txtCheckedBy.Enabled = true;
            }
            else
            {
                txtCheckedBy.Enabled = false;
            }
            if (Convert.ToInt32(DTFormatDetails.Rows[0]["REFERENCENUMBER"]) == 1)
            {
                txtRefNo.Enabled = true;
            }
            else
            {
                txtRefNo.Enabled = false;
            }
        }
    }
    protected void OverrideRow()
    {
        ControlCounter = (List<string>)ViewState["ControlCounter"];
        ddlServiceID = (List<string>)ViewState["ddlServiceID"];
        txtAdditionalID = (List<string>)ViewState["txtAdditionalID"];
        txtAmountID = (List<string>)ViewState["txtAmountID"];
        hidChkTaxableID = (List<string>)ViewState["hidChkTaxableID"];
        hiddebitnotechildID = (List<string>)ViewState["hiddebitnotechildID"];
        txtPECessID = (List<string>)ViewState["txtPECessID"];
        txtHECessID = (List<string>)ViewState["txtHECessID"];

        if (ControlCounter != null)
        {
             int count = Convert.ToInt32(ControlCounter.Count);

            for (int i = 0; i < count; i++)
            {
                rowcount++;
                HtmlTableRow htrow = new HtmlTableRow();
                HtmlTableCell htcell1 = new HtmlTableCell();
                htcell1.Align = "top";

                DropDownList ddlService = new DropDownList();
                ddlService.ID = ddlServiceID[i].ToString();
                ddlService.Width = Unit.Percentage(98);
                ddlService.SelectedIndex = 0;
                ddlService.ToolTip = "Service Name";
                ddlService.Attributes.Add("onchange", "checkItemRepetion(this.id)");
                fillService(ddlService);
                ddlService.AutoPostBack = true;
                ddlService.SelectedIndexChanged += new EventHandler(ddlService_SelectedIndexChanged);
                ddlService.CssClass = "dropdown";

                HiddenField hidChkTaxable = new HiddenField();
                hidChkTaxable.ID = hidChkTaxableID[i].ToString();

                htcell1.Controls.Add(ddlService);
                htcell1.Controls.Add(hidChkTaxable);
                htrow.Cells.Add(htcell1);

                HtmlTableCell htcell2 = new HtmlTableCell();
                htcell2.Align = "top";
                TextBox txtAdditional = new TextBox();
                txtAdditional.ID = txtAdditionalID[i].ToString();
                txtAdditional.Width = Unit.Percentage(98);
                txtAdditional.ToolTip = "Additional Description";
                txtAdditional.CssClass = "input";

                HiddenField hiddebitnotechild = new HiddenField();
                hiddebitnotechild.ID = hiddebitnotechildID[i].ToString();

                htcell2.Controls.Add(hiddebitnotechild);
                htcell2.Controls.Add(txtAdditional);
                htrow.Cells.Add(htcell2);

                HtmlTableCell htcell3 = new HtmlTableCell();
                htcell3.Align = "top";

                TextBox txtAmountService = new TextBox();
                txtAmountService.ID = txtAmountID[i].ToString();
                txtAmountService.Width = Unit.Percentage(98);
                txtAmountService.CssClass = "inputnumber";
                txtAmountService.MaxLength = 15;
                txtAmountService.Attributes.Add("onKeyPress", "return isNumberKey(this.id,event);");
                txtAmountService.Attributes.Add("onblur", "calTaxableNonTaxable();");
                txtAmountService.Attributes.Add("onfocus", "return SpecifiedService(this.id);");
                txtAmountService.AutoCompleteType = AutoCompleteType.None;
                htcell3.Controls.Add(txtAmountService);
                htrow.Cells.Add(htcell3);

                if (ViewState["rbtDebitNoteTypeValue"].ToString() == "2")
                {
                    HtmlTableCell htcell4 = new HtmlTableCell();
                    htcell4.Align = "top";

                    TextBox txtPECess = new TextBox();
                    txtPECess.ID = txtPECessID[i].ToString();
                    txtPECess.CssClass = "inputnumber";
                    txtPECess.Width = Unit.Percentage(98);
                    txtPECess.Attributes.Add("onKeyDown", "return EnabledTabKey(this.id, event);");
                    htcell4.Controls.Add(txtPECess);
                    htrow.Cells.Add(htcell4);

                    HtmlTableCell htcell5 = new HtmlTableCell();
                    htcell5.Align = "top";

                    TextBox txtHECess = new TextBox();
                    txtHECess.ID = txtHECessID[i].ToString();
                    txtHECess.CssClass = "inputnumber";
                    txtHECess.Width = Unit.Percentage(98);
                    txtHECess.Attributes.Add("onKeyDown", "return EnabledTabKey(this.id, event);");
                    htcell5.Controls.Add(txtHECess);
                    htrow.Cells.Add(htcell5);
                }

                tblService.Rows.Add(htrow);
            }
        }
    }
    protected void AddNewRow()
    {
        rowcount++;
        ControlCounter.Add(rowcount.ToString());

        HtmlTableRow htrow = new HtmlTableRow();
        HtmlTableCell htcell1 = new HtmlTableCell();
        htcell1.ID = "htcell1" + rowcount.ToString();
        htcell1.Align = "top";

        DropDownList ddlService = new DropDownList();
        ddlService.ID = "ddlService" + rowcount.ToString();
        ddlService.Width = Unit.Percentage(98);
        ddlService.SelectedIndex = 0;
        ddlService.ToolTip = "Service Name";
        ddlService.Attributes.Add("onchange", "checkItemRepetion(this.id)");
        fillService(ddlService);
        ddlService.AutoPostBack = true;
        ddlService.SelectedIndexChanged += new EventHandler(ddlService_SelectedIndexChanged);
        ddlService.CssClass = "dropdown";

        ddlServiceID.Add(ddlService.ID);

        HiddenField hidChkTaxable = new HiddenField();
        hidChkTaxable.ID = "hidChkTaxable" + rowcount.ToString();
        hidChkTaxableID.Add(hidChkTaxable.ID);

        htcell1.Controls.Add(ddlService);
        htcell1.Controls.Add(hidChkTaxable);
        htrow.Cells.Add(htcell1);

        HtmlTableCell htcell2 = new HtmlTableCell();
        htcell2.ID = "htcell2" + rowcount.ToString();
        htcell2.Align = "top";

        TextBox txtAdditional = new TextBox();
        txtAdditional.ID = "txtAdditional" + rowcount.ToString();
        txtAdditional.Width = Unit.Percentage(98);
        txtAdditional.ToolTip = "Additional Description";
        txtAdditional.CssClass = "input";
        txtAdditionalID.Add(txtAdditional.ID);

        HiddenField hiddebitnotechild = new HiddenField();
        hiddebitnotechild.ID = "hiddebitnotechild" + rowcount.ToString();
        hiddebitnotechildID.Add(hiddebitnotechild.ID);
        htcell2.Controls.Add(hiddebitnotechild);
        htcell2.Controls.Add(txtAdditional);
        htrow.Cells.Add(htcell2);

        HtmlTableCell htcell3 = new HtmlTableCell();
        htcell3.ID = "htcell3" + rowcount.ToString();
        htcell3.Align = "top";

        TextBox txtAmountService = new TextBox();
        txtAmountService.ID = "txtAmountService" + rowcount.ToString();
        txtAmountService.Width = Unit.Percentage(98);
        txtAmountService.CssClass = "inputnumber";
        txtAmountService.MaxLength = 15;
        txtAmountService.Attributes.Add("onKeyPress", "return isNumberKey(this.id,event);");
        txtAmountService.Attributes.Add("onblur", "calTaxableNonTaxable();");
        txtAmountService.Attributes.Add("onfocus", "return SpecifiedService(this.id);");
        txtAmountService.AutoCompleteType = AutoCompleteType.None;
        txtAmountID.Add(txtAmountService.ID);
        htcell3.Controls.Add(txtAmountService);
        htrow.Cells.Add(htcell3);

        if (ViewState["rbtDebitNoteTypeValue"].ToString() == "2")
        {
            HtmlTableCell htcell4 = new HtmlTableCell();
            htcell4.ID = "htcell4" + rowcount.ToString();
            htcell4.Align = "top";

            TextBox txtPECess = new TextBox();
            txtPECess.ID = "txtPECess" + rowcount.ToString();
            txtPECess.CssClass = "inputnumber";
            txtPECess.Width = Unit.Percentage(98);
            txtPECess.Attributes.Add("onKeyDown", "return EnabledTabKey(this.id, event);");
            txtPECessID.Add(txtPECess.ID);
            htcell4.Controls.Add(txtPECess);
            htrow.Cells.Add(htcell4);

            HtmlTableCell htcell5 = new HtmlTableCell();
            htcell5.ID = "htcell5" + rowcount.ToString();
            htcell5.Align = "top";

            TextBox txtHECess = new TextBox();
            txtHECess.ID = "txtHECess" + rowcount.ToString();
            txtHECess.CssClass = "inputnumber";
            txtHECess.Width = Unit.Percentage(98);
            txtHECess.Attributes.Add("onKeyDown", "return EnabledTabKey(this.id, event);");
            txtHECessID.Add(txtHECess.ID);
            htcell5.Controls.Add(txtHECess);
            htrow.Cells.Add(htcell5);
            ViewState["txtPECessID"] = txtPECessID;
            ViewState["txtHECessID"] = txtHECessID;
        }
        tblService.Rows.Add(htrow);
        ViewState["ddlServiceID"] = ddlServiceID;
        ViewState["txtAdditionalID"] = txtAdditionalID;
        ViewState["txtAmountID"] = txtAmountID;
        ViewState["hidChkTaxableID"] = hidChkTaxableID;
        ViewState["hiddebitnotechildID"] = hiddebitnotechildID;
        hiddentControl.Value = rowcount.ToString();
    }
    protected void DeleteOneRow()
    {
        int rowcount = Convert.ToInt32(hiddentControl.Value);
        int rowindex = rowcount;
        int tablerow = Convert.ToInt32(tblService.Rows.Count);
        if (rowcount > 1)
        {
            if (rowcount == tablerow - 1)
            {
                ControlCounter = (List<string>)ViewState["ControlCounter"];
                ddlServiceID = (List<string>)ViewState["ddlServiceID"];
                txtAdditionalID = (List<string>)ViewState["txtAdditionalID"];
                txtAmountID = (List<string>)ViewState["txtAmountID"];
                hidChkTaxableID = (List<string>)ViewState["hidChkTaxableID"];
                hiddebitnotechildID = (List<string>)ViewState["hiddebitnotechildID"];
                if (rbtDebitNoteType.SelectedIndex == 2)
                {
                    txtPECessID = (List<string>)ViewState["txtPECessID"];
                    txtHECessID = (List<string>)ViewState["txtHECessID"];
                }

                tblService.Rows.RemoveAt(rowcount);
                rowindex = rowcount - 1;
                ControlCounter.RemoveAt(rowcount - 2);
                ddlServiceID.RemoveAt(rowcount - 2);
                txtAdditionalID.RemoveAt(rowcount - 2);
                txtAmountID.RemoveAt(rowcount - 2);
                hidChkTaxableID.RemoveAt(rowcount - 2);
                hiddebitnotechildID.RemoveAt(rowcount - 2);
                if (ViewState["rbtDebitNoteTypeValue"].ToString() == "2")
                {
                    txtPECessID.RemoveAt(rowcount - 2);
                    txtHECessID.RemoveAt(rowcount - 2);
                    ViewState["txtPECessID"] = txtPECessID;
                    ViewState["txtHECessID"] = txtHECessID;
                }

                ViewState["ControlCounter"] = ControlCounter;
                ViewState["ddlServiceID"] = ddlServiceID;
                ViewState["txtAdditionalID"] = txtAdditionalID;
                ViewState["txtAmountID"] = txtAmountID;
                ViewState["hidChkTaxableID"] = hidChkTaxableID;
                ViewState["hiddebitnotechildID"] = hiddebitnotechildID;
                hiddentControl.Value = rowindex.ToString();
            }
        }
    }
    protected void fillBillFormat()
    {
        DataTable dtBillFormat = new DataTable();
        SqlParameter[] trantype =
        {
            new SqlParameter("@TRANSACTIONTYPE","3")
        };
        dtBillFormat = DU.getdatausingprocedure("USP_IVC_GetAllTransactionFormatNameID", trantype);
        ddlBillFormat.DataSource = dtBillFormat;
        ddlBillFormat.DataValueField = "FORMATID";
        ddlBillFormat.DataTextField = "FORMATNAME";
        ddlBillFormat.DataBind();
    }
    protected void fillCustomerName()
    {
        DataTable dtFillCustomer = new DataTable();
        dtFillCustomer = DU.getdatausingprocedure("USP_IVC_GetCustomerLedger");
        if (dtFillCustomer.Rows.Count > 0)
        {
            ddlCustomer.DataValueField = "LID";
            ddlCustomer.DataTextField = "LNAME";
            ddlCustomer.DataSource = dtFillCustomer;
            ddlCustomer.DataBind();
            ddlCustomer.Items.Insert(0, new ListItem("--Select Customer--", "0"));
        }
        else
        {
            ddlCustomer.Items.Insert(0, new ListItem("--No Customer Found--", "0"));
        }
    }
    protected void clearTaxableCalc()
    {
        txtServiceTax.Text = "";
        txtTaxable.Text = "";
        txtNonTaxable.Text = "";
        txtHECess.Text = "";
        txtPECess.Text = "";
        txtTotalAmount.Text = "";
    }
    private void fillService(DropDownList ddl)
    {
        SqlParameter[] taxability = {
                                       new SqlParameter("@SERVICETAXTYPE",ViewState["rbtDebitNoteTypeValue"].ToString())
                                    };

        DataTable dtFillService = DU.getdatausingprocedure("USP_IVC_GetServiceNameIdForDebitNote", taxability);
        if (dtFillService.Rows.Count > 0)
        {
            ddl.DataSource = dtFillService;
            ddl.DataValueField = "SERVICEID";
            ddl.DataTextField = "SERVICENAME";
            ddl.DataBind();
            ddl.Items.Insert(0, new ListItem("--Select Service--", "0"));
        }
        else
        {
            ddl.Items.Insert(0, new ListItem("--No Service Found--", "0"));
        }
    }
    protected void DeleteAllRowOnRadioClick()
    {
        int rowcnt = Convert.ToInt32(hiddentControl.Value);
        int rowindex = rowcount;
        int tablerow = Convert.ToInt32(tblService.Rows.Count);
        for (int i = rowcnt; i > 1; i--)
        {
            if (rowcnt > 1)
            {
                if (rowcnt == tablerow - 1)
                {
                    ControlCounter = (List<string>)ViewState["ControlCounter"];
                    ddlServiceID = (List<string>)ViewState["ddlServiceID"];
                    txtAdditionalID = (List<string>)ViewState["txtAdditionalID"];
                    txtAmountID = (List<string>)ViewState["txtAmountID"]; 
                    hidChkTaxableID = (List<string>)ViewState["hidChkTaxableID"];
                    hiddebitnotechildID = (List<string>)ViewState["hiddebitnotechildID"];
                    if (Convert.ToInt32(ViewState["rbtDebitNoteTypeValue"].ToString()) == 2)
                    {
                        txtPECessID = (List<string>)ViewState["txtPECessID"];
                        txtHECessID = (List<string>)ViewState["txtHECessID"];
                    }

                    tblService.Rows.RemoveAt(rowcnt);
                    rowindex = rowcnt - 1;
                    ControlCounter.RemoveAt(rowcnt - 2);
                    ddlServiceID.RemoveAt(rowcnt - 2);
                    txtAdditionalID.RemoveAt(rowcnt - 2);
                    txtAmountID.RemoveAt(rowcnt - 2);
                    hidChkTaxableID.RemoveAt(rowcnt - 2);
                    hiddebitnotechildID.RemoveAt(rowcnt - 2);
                    if (ViewState["rbtDebitNoteTypeValue"].ToString() == "2")
                    {
                        if (Convert.ToInt32(txtPECessID.Count) > 0)
                        {
                            txtPECessID.RemoveAt(rowcnt - 2);
                            txtHECessID.RemoveAt(rowcnt - 2);
                            ViewState["txtPECessID"] = txtPECessID;
                            ViewState["txtHECessID"] = txtHECessID;
                        }
                    }

                    ViewState["ControlCounter"] = ControlCounter;
                    ViewState["ddlServiceID"] = ddlServiceID;
                    ViewState["txtAdditionalID"] = txtAdditionalID;
                    ViewState["txtAmountID"] = txtAmountID; 
                    ViewState["hidChkTaxableID"] = hidChkTaxableID;
                    ViewState["hiddebitnotechildID"] = hiddebitnotechildID;
                    hiddentControl.Value = rowindex.ToString();
                    tablerow--;
                    rowcnt--;
                    rowindex--;
                }
            }
        }
        clearTaxableCalc();
        txtAdditional1.Text = "";
        txtAmountService1.Text = "";
        txtPECess1.Text = "";
        txtHECess1.Text = "";
    }    
    protected void fillServicePEHETax(string strCurrentDate)
    {
        if (strCurrentDate != string.Empty)
        {
            string[] str = strCurrentDate.ToString().Split('/');
            strCurrentDate = str[1] + "/" + str[0] + "/" + str[2];
            SqlParameter[] gettaxrate = 
                                        {
                                            new SqlParameter("@CURRENTDATE",strCurrentDate)
                                        };
            DataTable dtFillTaxes = DU.getdatausingprocedure("USP_IVC_GetCurrentServiceTaxRate", gettaxrate);
            if (dtFillTaxes.Rows.Count > 0)
            {
                txtServiceTaxPer.Text = string.Format("{0:0.00}", Convert.ToDouble(dtFillTaxes.Rows[0]["SERVICETAX"].ToString()));
                txtPECessPer.Text = string.Format("{0:0.00}", Convert.ToDouble(dtFillTaxes.Rows[0]["PCess"].ToString()));
                txtHECessPer.Text = string.Format("{0:0.00}", Convert.ToDouble(dtFillTaxes.Rows[0]["HCess"].ToString()));

                hidServiceTaxRate.Value = string.Format("{0:0.00}", Convert.ToDouble(dtFillTaxes.Rows[0]["SERVICETAX"].ToString()));
                hidPECessRate.Value = string.Format("{0:0.00}", Convert.ToDouble(dtFillTaxes.Rows[0]["PCess"].ToString()));
                hidHECessRate.Value = string.Format("{0:0.00}", Convert.ToDouble(dtFillTaxes.Rows[0]["HCess"].ToString()));

                hidServiceTaxLid.Value = dtFillTaxes.Rows[0]["SERVICETAX_LID"].ToString();
                hidPECessLid.Value = dtFillTaxes.Rows[0]["PCess_LID"].ToString();
                hidHECessLid.Value = dtFillTaxes.Rows[0]["HCess_LID"].ToString();
            }
        }
    }
    #endregion 

    #region /*Event*/
    protected void rbtDebitNoteType_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (rbtDebitNoteType.SelectedValue == "0")
        {
            lblAmount.Text = "Amount";
            lblHECess.Visible = false;
            txtHECess1.Visible = false;
            lblPECess.Visible = false;
            txtPECess1.Visible = false;
            lblServiceTax.Text = "Service Tax %";
            txtServiceTaxPer.Visible = true;
            lblPECess1.Text = "P.E.Cess %";
            txtPECessPer.Visible = true;
            lblHECess1.Text = "H.E.Cess %";
            txtHECessPer.Visible = true;
            DeleteAllRowOnRadioClick();
            ViewState["rbtDebitNoteTypeValue"] = "0";
            ddlService1.Items.Clear();
            fillService(ddlService1);
        }
        else if (rbtDebitNoteType.SelectedValue == "1")
        {
            lblAmount.Text = "Amount";
            lblHECess.Visible = false;
            txtHECess1.Visible = false;
            lblPECess.Visible = false;
            txtPECess1.Visible = false;
            lblServiceTax.Text = "Service Tax ";
            txtServiceTaxPer.Visible = false;
            lblPECess1.Text = "P.E.Cess";
            txtPECessPer.Visible = false;
            lblHECess1.Text = "H.E.Cess";
            txtHECessPer.Visible = false;
            DeleteAllRowOnRadioClick();
            ViewState["rbtDebitNoteTypeValue"] = "1";
            ddlService1.Items.Clear();
            fillService(ddlService1);
        }
        else if (rbtDebitNoteType.SelectedValue == "2")
        {
            lblAmount.Text = "Service Tax";
            lblHECess.Visible = true;
            txtHECess1.Visible = true;
            lblPECess.Visible = true;
            txtPECess1.Visible = true;
            lblServiceTax.Text = "Service Tax";
            txtServiceTaxPer.Visible = false;
            lblPECess1.Text = "P.E.Cess %";
            txtPECessPer.Visible = true;
            lblHECess1.Text = "H.E.Cess %";
            txtHECessPer.Visible = true;
            DeleteAllRowOnRadioClick();
            ViewState["rbtDebitNoteTypeValue"] = "2";
            if (txtDate.Text != "")
            {
                fillServicePEHETax(txtDate.Text);
            }
            ddlService1.Items.Clear();
            fillService(ddlService1);
        }
    }
    protected void btnAddMore_Click(object sender, EventArgs e)
    {
        AddNewRow();
    }
    protected void btnDelete_Click(object sender, EventArgs e)
    {
        DeleteOneRow();
    }
    protected void ddlBillFormat_SelectedIndexChanged(object sender, EventArgs e)
    {
        CheckRef();
        string strFinyear = Session["FINYEAR"].ToString();
        if (strFinyear != string.Empty)
        {
            SqlParameter[] sparam =
                                    {
                                        new SqlParameter("@TFOID",ddlBillFormat.SelectedValue),
                                        new SqlParameter ("@FINYEAR",strFinyear)
                                    };
            DataTable DTVoucher = DU.getdatausingprocedure("USP_IVC_GetMaxVoucherNo", sparam);
            if (DTVoucher.Rows.Count > 0)
            {
                txtPrefix.Text = DTVoucher.Rows[0]["prefix"].ToString();
                txtDebitNoteNo.Text = DTVoucher.Rows[0]["vouno"].ToString();
                txtSuffix.Text = DTVoucher.Rows[0]["suffix"].ToString();
            }
        }
    }
    protected void ddlService_SelectedIndexChanged(object sender, EventArgs e)
    {
        DropDownList ddl = (DropDownList)sender;
        if (ddl.SelectedIndex > 0)
        {
            string ddlid = ddl.ID.ToString().Substring(10);
            int rowIndex = Convert.ToInt32(ddlid.ToString());
            strsql = "select taxability,subclass from IVC_SERVICEMASTER where serviceid='" + ddl.SelectedValue.ToString() + "'";
            DataTable DTTax = DU.getdata(strsql);
            HiddenField hidChkTaxable = (HiddenField)tblService.Rows[rowIndex].FindControl("hidChkTaxable" + rowIndex.ToString());
            if (DTTax.Rows.Count > 0)
            {
                if (DTTax.Rows[0]["taxability"].ToString() == "0" && DTTax.Rows[0]["subclass"].ToString() == "1")
                {
                    hidChkTaxable.Value = "1";
                }
                else
                {
                    hidChkTaxable.Value = "0";
                }
            }
        }
    }
    protected void txtDate_TextChanged(object sender, EventArgs e)
    {
        if (txtDate.Text != string.Empty)
        {
            fillServicePEHETax(txtDate.Text);
        }
    }
    private string _GetServiceLedgerId(string strServiceId)
    {
        string strLedgerId = string.Empty;
        if (strServiceId != string.Empty)
        {
            strsql = "SELECT LEDGERID FROM IVC_SERVICEMASTER WHERE SERVICEID='" + strServiceId + "'";
            DataTable DTLedger = DU.getdata(strsql);
            if (DTLedger.Rows.Count > 0)
            {
                strLedgerId = DTLedger.Rows[0]["LEDGERID"].ToString();
            }
        }
        return strLedgerId;
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        try
        {
            using (TransactionScope scope = new TransactionScope())
            {
                _SaveVouchers();
                _SaveVouchers_Details();
               
                _SaveDebitNote_Main(Request.QueryString["tranid"].ToString());
                scope.Complete();
                lblMsg.Text = "Debit Note Updated Succesfully...";
            }
        }
        catch (Exception ex)
        {
            lblMsg.Text = ex.Message;
        }
    }
    protected void btnClose_Click(object sender, EventArgs e)
    {
        Response.Redirect("~/Welcome.aspx");
    }
    #endregion

    #region /*Bind */
    protected void bindmain()
    {
        SqlParameter[] parm1 = { new SqlParameter("@Debitnoteid", Request.QueryString["debitnoteid"].ToString()) };
        DataTable dt = DU.getdatausingprocedure("USP_IVC_GetDebittnotedetailBy_DebitnoteId", parm1);
        if (dt.Rows.Count > 0)
        {
           
            txtPreparedBy.Text = dt.Rows[0]["PREPAREDBY"].ToString();
            txtCheckedBy.Text = dt.Rows[0]["CHECKEDBY"].ToString();
            txtRemarks.Text = dt.Rows[0]["REMARKS"].ToString();           
            string customer = dt.Rows[0]["CUSTOMERLEDGERID"].ToString();
            ddlCustomer.SelectedValue = customer;
            string Billformat = dt.Rows[0]["FORMATID"].ToString();
            ddlBillFormat.SelectedValue = Billformat;
            rbtDebitNoteType.SelectedValue = dt.Rows[0]["DEBITENOTETOWARDS"].ToString();    
            ViewState["rbtDebitNoteTypeValue"] = dt.Rows[0]["DEBITENOTETOWARDS"].ToString();
           
            for (int i = 1; i < dt.Rows.Count; i++)
                {
                    AddNewRow();
                }
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                DropDownList ddlService = (DropDownList)tblService.FindControl("ddlService" + (i + 1));
                TextBox txtAdditional = (TextBox)tblService.FindControl("txtAdditional" + (i + 1));
                TextBox txtAmountService = (TextBox)tblService.FindControl("txtAmountService" + (i + 1));
                TextBox txtPECess = (TextBox)tblService.FindControl("txtPECess" + (i + 1));
                TextBox txtHECess = (TextBox)tblService.FindControl("txtHECess" + (i + 1));
                HiddenField hiddebitnotechild = (HiddenField)tblService.FindControl("hiddebitnotechild" + (i + 1));

                fillService(ddlService);
                string Service_ddl = dt.Rows[i]["ServiceID"].ToString();
                ddlService.SelectedValue = Service_ddl;
                txtAdditional.Text = dt.Rows[i]["ADDDESC"].ToString();
                hiddebitnotechild.Value = dt.Rows[i]["DEBITNOTECHILDID"].ToString();

                if (dt.Rows[0]["DEBITENOTETOWARDS"].ToString() == "0")
                {
                    lblAmount.Text = "Amount";
                    txtAmountService.Text = dt.Rows[i]["Amount"].ToString();
                    lblHECess.Visible = false;
                    txtHECess1.Visible = false;
                    lblPECess.Visible = false;
                    txtPECess1.Visible = false;
                }

                if (dt.Rows[0]["DEBITENOTETOWARDS"].ToString() == "1")
                {
                    txtAmountService.Text = dt.Rows[i]["Amount"].ToString();
                    lblAmount.Text = "Amount";
                    lblHECess.Visible = false;
                    txtHECess1.Visible = false;
                    lblPECess.Visible = false;
                    txtPECess1.Visible = false;

                    txtPECess.Visible = false;
                    txtHECess.Visible = false;

                    lblServiceTax.Text = "Service Tax %";
                    txtServiceTaxPer.Visible = false;
                    lblPECess1.Text = "P.E.Cess %";
                    txtPECessPer.Visible = false;
                    lblHECess1.Text = "H.E.Cess %";
                    txtHECessPer.Visible = false;
                }
                
                if (dt.Rows[0]["DEBITENOTETOWARDS"].ToString() == "2")
                {
                    lblAmount.Text = "Service Tax";
                    lblHECess.Visible = true;
                    txtHECess1.Visible = true;
                    lblPECess.Visible = true;
                    txtPECess1.Visible = true;

                    txtPECess.Visible = true;
                    txtHECess.Visible = true;

                    lblServiceTax.Text = "Service Tax %";
                    txtServiceTaxPer.Visible = false;
                    lblPECess1.Text = "P.E.Cess %";
                    txtPECessPer.Visible = true;
                    lblHECess1.Text = "H.E.Cess %";
                    txtHECessPer.Visible = true;

                    txtAmountService.Text = dt.Rows[i]["SERVICETAXAMT"].ToString();
                    txtPECess.Text = dt.Rows[i]["EDUCESS1AMT"].ToString();
                    txtHECess.Text = dt.Rows[i]["EDUCESS2AMT"].ToString();
                }

            }
            BindDebitnotechild();
            
        }
        
    }
    protected void BindDebitnotechild()
    {
        SqlParameter[] parm1 = { new SqlParameter("@DEBITNOTEID", Request.QueryString["DEBITNOTEID"].ToString()) };
        DataTable dt1 = DU.getdatausingprocedure("USP_IVC_GetDebittnoteTotalBy_DebitnoteId", parm1);
        //string sql = "select TAXABLEAMT, NONTAXABLEAMT, SERVICETAXRATE, SERVICETAXAMT, EDUCESS1AMT, EDUCESS1RATE, EDUCESS1RATE, EDUCESS2AMT, EDUCESS2RATE, TOTAL from IVC_DEBITNOTE_TOTAL where DEBITNOTEID =" + Request.QueryString["debitnoteid"].ToString();
       
        if (dt1.Rows.Count > 0)
        {
            txtServiceTax.Text = dt1.Rows[0]["SERVICETAXAMT"].ToString();
            //txtServiceTaxPer.Text = dt1.Rows[0]["SERVICETAXRATE"].ToString();
            txtNonTaxable.Text = dt1.Rows[0]["NONTAXABLEAMT"].ToString();
            txtTaxable.Text = dt1.Rows[0]["TAXABLEAMT"].ToString();
            txtTotalAmount.Text = dt1.Rows[0]["Total"].ToString();
            txtPECess.Text = dt1.Rows[0]["EDUCESS1AMT"].ToString();
            txtHECess.Text = dt1.Rows[0]["EDUCESS2AMT"].ToString();
        }
        BindVoucher(Request.QueryString["TRANID"].ToString());

    }
    protected void BindVoucher(string tranid )
    {
        SqlParameter[] parm1 = { new SqlParameter("@TRANID", Request.QueryString["TRANID"].ToString()) };
        DataTable dt = DU.getdatausingprocedure("USP_IVC_GetDebitnoteVoucherBy_Tranid", parm1);
        //string sql = "select VOUNO, VOUDATE, REFNO, NARRATION from ACC_VOUCHERS where TRANID = " + tranid;
        if (dt.Rows.Count > 0)
        {
            txtDebitNoteNo.Text = dt.Rows[0]["VOUNO"].ToString();
            txtRefNo.Text = dt.Rows[0]["REFNO"].ToString();
            txtNarration.Text = dt.Rows[0]["NARRATION"].ToString();
            txtDate.Text = (String.Format("{0:dd/MM/yyyy}", Convert.ToDateTime(dt.Rows[0]["voudate"].ToString())));
        }

        SqlParameter[] parm2 = { new SqlParameter("@TRANID", Request.QueryString["TRANID"].ToString()) };
        DataTable dt1 = DU.getdatausingprocedure("USP_IVC_GetDebitnoteVoucherDetailsBy_Tranid", parm2);
       // string sql2 = "select ACC_VOUDETAILS.VOUSERIAL as VOUSERIAL, ACC_REFDETAILS.REFSERIAL as REFSERIAL, ACC_REFDETAILS.PARENTREF as PARENTREF from ACC_VOUDETAILS inner join ACC_REFDETAILS on ACC_REFDETAILS.VOUSERIAL = ACC_VOUDETAILS.VOUSERIAL where TRANID =" + tranid;
       // DataTable dt1 = DU.getdata(sql2);
        hidvouserial.Value = dt1.Rows[0]["VOUSERIAL"].ToString();
        hidrefserial.Value = dt1.Rows[0]["REFSERIAL"].ToString();
        hidParentref.Value = dt1.Rows[0]["PARENTREF"].ToString();
    }
  
    
    #endregion

    #region /* Save */
    private string _SaveVouchers()
    {
        string strTranId = string.Empty;
        try
        {
            string strTranDate = string.Empty;
            string strTranTypeId = string.Empty;
            if (txtDate.Text != string.Empty)
            {
                string[] strTemp = txtDate.Text.Split('/');
                strTranDate = strTemp[1] + "/" + strTemp[0] + "/" + strTemp[2];
            }
            SqlParameter[] sparam ={
                                    new SqlParameter("@PARENTTYPEID","3"),
                                    new SqlParameter("@BILLFORMATID",ddlBillFormat.SelectedValue),
                                    new SqlParameter("@MODULETYPE","3")
                                };
            DataTable DTTranTypeId = DU.getdatausingprocedure("USP_ACC_GetTransactionSettingBasedOnFormat", sparam);
            if (DTTranTypeId.Rows.Count > 0)
            {
                strTranTypeId = DTTranTypeId.Rows[0]["TypeID"].ToString();
            }
            if (strTranTypeId != string.Empty)
            {
                SqlParameter[] sparam1 = 
                                {
                                    new SqlParameter("@TransactionID", Request.QueryString["TRANID"].ToString()),
                                    new SqlParameter("@TransactionTypeID",strTranTypeId),      
                                    new SqlParameter("@TransactionNumber",txtDebitNoteNo.Text),      
                                    new SqlParameter("@FinYear",Session["FINYEAR"].ToString()),      
                                    new SqlParameter("@ReferenceNumber",txtRefNo.Text),     
                                    new SqlParameter("@IsCashVoucher","0"),      
                                    new SqlParameter("@TransactionDate",strTranDate),      
                                    new SqlParameter("@Narration",txtNarration.Text),     
                                    new SqlParameter("@CreditDays","0"),         
                                    new SqlParameter("@ModifiedBy",Session["userid"].ToString()),      
                                    new SqlParameter("@IsCancelled","0"),      
                                    new SqlParameter("@CostCentreClassID","0")  
                                };
                       DU.executeprocedure("USP_ACC_UpdateTransaction", sparam1);
                      
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
        return strTranId;
    }

    private void _SaveVouchers_Details()
    {
        try
        {
                string strTranDate = string.Empty;
                if (txtDate.Text != string.Empty)
                {
                    string[] strTemp = txtDate.Text.Split('/');
                    strTranDate = strTemp[1] + "/" + strTemp[0] + "/" + strTemp[2];
                }
                if (ddlCustomer.SelectedValue != "0")
                {
                    if (txtTotalAmount.Text != string.Empty && Convert.ToDouble(txtTotalAmount.Text) > 0)
                    {
                        double Amount = 0 - Convert.ToDouble(txtTotalAmount.Text);
                        SqlParameter[] sparam =
                                                {
                                                    new SqlParameter("@TransactionSerial", hidvouserial.Value),
                                                    new SqlParameter("@TransactionId",Request.QueryString["TRANID"].ToString()),
                                                    new SqlParameter("@LedgerId",ddlCustomer.SelectedValue),
                                                    new SqlParameter("@Amount",Amount),
                                                    new SqlParameter("@IsReconciled","0"),
                                                    new SqlParameter("@ReconciledDate",strTranDate)
                                                };
                        int result =DU.executeprocedure("USP_ACC_UpdateTransactionDetails", sparam);
                        if (result > 0)
                        {
                            strsql = "delete from acc_voudetails where tranid='" + Request.QueryString["TRANID"].ToString() + "' and vouserial<>'" + hidvouserial.Value + "'";
                            DU.executesql(strsql);
                            _SaveReference_Details(hidvouserial.Value);
                        }                              
                           
                    }
                }
                if (ViewState["rbtDebitNoteTypeValue"].ToString() == "0" || ViewState["rbtDebitNoteTypeValue"].ToString() == "1")
                {
                    int count = Convert.ToInt32(hiddentControl.Value);
                    for (int i = 1; i <= count; i++)
                    {
                        DropDownList ddlService = (DropDownList)tblService.Rows[i].FindControl("ddlService" + i);
                        TextBox txtAmountService = (TextBox)tblService.Rows[i].FindControl("txtAmountService" + i);
                        if (ddlService.SelectedValue != "0")
                        {
                            string strServiceLid = _GetServiceLedgerId(ddlService.SelectedValue);
                            if (txtAmountService.Text != string.Empty && Convert.ToDouble(txtAmountService.Text) > 0 && strServiceLid != string.Empty)
                            {
                                SqlParameter[] sparam =
                                            {                                                
                                                new SqlParameter("@TransactionId",Request.QueryString["TRANID"].ToString()),
                                                new SqlParameter("@LedgerId",strServiceLid),
                                                new SqlParameter("@Amount",txtAmountService.Text),
                                                new SqlParameter("@IsReconciled","0"),
                                                new SqlParameter("@ReconciledDate",strTranDate)
                                            };
                                DU.executeprocedure("USP_ACC_SaveTransactionDetails", sparam);
                            }
                        }
                    }
                }
                if (txtServiceTax.Text != string.Empty && Convert.ToDouble(txtServiceTax.Text) > 0 && hidServiceTaxLid.Value != string.Empty)
                {

                    SqlParameter[] sparam =
                                                {                                                   
                                                    new SqlParameter("@TransactionId",Request.QueryString["TRANID"].ToString()),
                                                    new SqlParameter("@LedgerId",hidServiceTaxLid.Value),
                                                    new SqlParameter("@Amount",txtServiceTax.Text),
                                                    new SqlParameter("@IsReconciled","0"),
                                                    new SqlParameter("@ReconciledDate",strTranDate)
                                                };
                    DU.executeprocedure("USP_ACC_SaveTransactionDetails", sparam);

                }
                if (txtPECess.Text != string.Empty && Convert.ToDouble(txtPECess.Text) > 0 && hidPECessLid.Value != string.Empty)
                {
                    SqlParameter[] sparam =
                                            {
                                                
                                                new SqlParameter("@TransactionId",Request.QueryString["TRANID"].ToString()),
                                                new SqlParameter("@LedgerId",hidPECessLid.Value),
                                                new SqlParameter("@Amount",txtPECess.Text),
                                                new SqlParameter("@IsReconciled","0"),
                                                new SqlParameter("@ReconciledDate",strTranDate)
                                            };
                    DU.executeprocedure("USP_ACC_SaveTransactionDetails", sparam);

                }
                if (txtHECess.Text != string.Empty && Convert.ToDouble(txtHECess.Text) > 0 && hidHECessLid.Value != string.Empty)
                {

                    SqlParameter[] sparam =
                                                {
                                                    
                                                    new SqlParameter("@TransactionId",Request.QueryString["TRANID"].ToString()),
                                                    new SqlParameter("@LedgerId",hidHECessLid.Value),
                                                    new SqlParameter("@Amount",txtHECess.Text),
                                                    new SqlParameter("@IsReconciled","0"),
                                                    new SqlParameter("@ReconciledDate",strTranDate)
                                                };
                    DU.executeprocedure("USP_ACC_SaveTransactionDetails", sparam);
                }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    private void _SaveReference_Details(string strVouSerial)
    {
        try
        {
            if (strVouSerial != string.Empty)
            {
                decimal Amount = 0;
                string strRefDate = string.Empty;
                string strRefferenceNo = string.Empty;
                if (txtDate.Text.ToString() != string.Empty)
                {
                    string[] str = txtDate.Text.ToString().Split('/');
                    strRefDate = str[1].ToString() + "/" + str[0].ToString() + "/" + str[2].ToString();
                }
                if (txtTotalAmount.Text != string.Empty)
                {
                    Amount = 0 - Convert.ToDecimal(txtTotalAmount.Text.Trim());
                }
                strsql = "SELECT FORMATNAME FROM IVC_TRANSACTIONFORMAT WHERE FORMATID='" + ddlBillFormat.SelectedValue + "'";
                DataTable DTFormatName = DU.getdata(strsql);
                if (DTFormatName.Rows.Count > 0)
                {
                    strRefferenceNo += DTFormatName.Rows[0]["FORMATNAME"].ToString() + " ";
                    if (txtPrefix.Text != string.Empty)
                    {
                        strRefferenceNo += txtPrefix.Text + "/";
                    }
                    strRefferenceNo += txtDebitNoteNo.Text;
                    if (txtSuffix.Text != string.Empty)
                    {
                        strRefferenceNo += "/" + txtSuffix.Text;
                    }
                }
                SqlParameter[] sparam = {
                                            new SqlParameter("@ReferenceSerial", hidrefserial.Value),
                                            new SqlParameter("@ParentReference", hidrefserial.Value),
                                            new SqlParameter("@TransactionSerial",strVouSerial),
                                            new SqlParameter("@ReferenceType","1"),
                                            new SqlParameter("@Reference",strRefferenceNo),
                                            new SqlParameter("@ReferenceDate",strRefDate),
                                            new SqlParameter("@CreditDays","0"),
                                            new SqlParameter("@ReferenceAmount",Amount),
                                            new SqlParameter("@IsTDSDeducted","0")
                                };
               
                DU.executeprocedure("USP_ACC_SaveReferenceDetails", sparam);
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    private void _SaveDebitNote_Main(string strTranId)
    {
        try
        {
            if (strTranId != string.Empty)
            {
                SqlParameter[] sparam = 
                                {
                                    new SqlParameter("@DEBITNOTEID", Request.QueryString["debitnoteid"].ToString()),      
                                    new SqlParameter("@CUSTOMERLEDGERID",ddlCustomer.SelectedValue),      
                                    new SqlParameter("@FORMATID",ddlBillFormat.SelectedValue),      
                                    new SqlParameter("@TRANID",strTranId),      
                                    new SqlParameter("@REMARKS",txtRemarks.Text),      
                                    new SqlParameter("@CHECKEDBY",txtCheckedBy.Text),      
                                    new SqlParameter("@PREPAREDBY",txtPreparedBy.Text),     
                                    new SqlParameter("@ISTDSAPPLIED","0"),                                        
                                    new SqlParameter("@DEBITENOTETOWARDS",rbtDebitNoteType.SelectedValue) 
                                };
                 DU.executeprocedure("USP_IVC_SaveDebitNote", sparam);

                 _SaveDebitNote_Child(Request.QueryString["debitnoteid"].ToString());
                 _SaveDebitNote_Total(Request.QueryString["debitnoteid"].ToString());
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    private void _SaveDebitNote_Child(string strDebitNoteId)
    {
        try
        {
            if (strDebitNoteId != string.Empty)
            {
                int count = Convert.ToInt32(hiddentControl.Value);
                if (ViewState["rbtDebitNoteTypeValue"].ToString() == "0" || ViewState["rbtDebitNoteTypeValue"].ToString() == "1")
                {
                    for (int i = 1; i <= count; i++)
                    {
                        DropDownList ddlService = (DropDownList)tblService.Rows[i].FindControl("ddlService" + i);
                        HiddenField hidChkTaxable = (HiddenField)tblService.Rows[i].FindControl("hidChkTaxable" + i);
                        TextBox txtAdditional = (TextBox)tblService.Rows[i].FindControl("txtAdditional" + i);
                        TextBox txtAmountService = (TextBox)tblService.Rows[i].FindControl("txtAmountService" + i);
                        HiddenField hiddebitnotechild = (HiddenField)tblService.Rows[i].FindControl("hiddebitnotechild" + i);
                        if (ddlService.SelectedValue == "0" && hiddebitnotechild.Value.Length > 0)
                        {

                            strsql = "delete from IVC_DEBITNOTE_CHILD where DEBITNOTECHILDID ='" + hiddebitnotechild.Value + "'";
                            DU.executesql(strsql);
                        }
                        if (ddlService.SelectedValue != "0")
                        {
                        if (txtAmountService.Text != string.Empty && Convert.ToDouble(txtAmountService.Text) > 0)
                        {
                            double dblServiceTax = 0;
                            double dblPECess = 0;
                            double dblHECess = 0;
                            if (hidChkTaxable.Value == "1")
                            {
                                dblServiceTax = Convert.ToDouble(txtAmountService.Text) * Convert.ToDouble(hidServiceTaxRate.Value) / 100;
                                dblPECess = Convert.ToDouble(txtAmountService.Text) * Convert.ToDouble(hidPECessRate.Value) / 100;
                                dblHECess = Convert.ToDouble(txtAmountService.Text) * Convert.ToDouble(hidHECessRate.Value) / 100;
                            }
                           
                                SqlParameter[] sparam =
                                    {
                                          new SqlParameter("@DEBITNOTECHILDID",hiddebitnotechild.Value), 
                                          new SqlParameter("@DEBITNOTEID",strDebitNoteId),      
                                          new SqlParameter("@SERVICEID",ddlService.SelectedValue),      
                                          new SqlParameter("@ADDDESC",txtAdditional.Text),      
                                          new SqlParameter("@SERVICETAXAMT",dblServiceTax),      
                                          new SqlParameter("@EDUCESS1AMT",dblPECess),     
                                          new SqlParameter("@EDUCESS2AMT",dblHECess),
                                          new SqlParameter("@AMOUNT",txtAmountService.Text)
                                    };
                                DU.executeprocedure("USP_IVC_SaveDebitNoteServiceDetails", sparam);
                            }
                        }
                       
                    }
                }
                else if (ViewState["rbtDebitNoteTypeValue"].ToString() == "2")
                {
                    for (int i = 1; i <= count; i++)
                    {
                        DropDownList ddlService = (DropDownList)tblService.Rows[i].FindControl("ddlService" + i);
                        TextBox txtAdditional = (TextBox)tblService.Rows[i].FindControl("txtAdditional" + i);
                        TextBox txtAmountService = (TextBox)tblService.Rows[i].FindControl("txtAmountService" + i);
                        TextBox txtPECess = (TextBox)tblService.Rows[i].FindControl("txtPECess" + i);
                        TextBox txtHECess = (TextBox)tblService.Rows[i].FindControl("txtHECess" + i);
                        HiddenField hiddebitnotechild = (HiddenField)tblService.Rows[i].FindControl("hiddebitnotechild" + i);
                        if (ddlService.SelectedValue == "0" && hiddebitnotechild.Value.Length > 0)
                        {

                            strsql = "delete from IVC_DEBITNOTE_CHILD where DEBITNOTECHILDID ='" + hiddebitnotechild.Value + "'";
                            DU.executesql(strsql);
                        }
                        if (txtAmountService.Text != string.Empty && Convert.ToDouble(txtAmountService.Text) > 0)
                        {
                            SqlParameter[] sparam =
                                    {
                                          new SqlParameter("@DEBITNOTECHILDID",hiddebitnotechild.Value), 
                                          new SqlParameter("@DEBITNOTEID",strDebitNoteId),      
                                          new SqlParameter("@SERVICEID",ddlService.SelectedValue),      
                                          new SqlParameter("@ADDDESC",txtAdditional.Text),      
                                          new SqlParameter("@SERVICETAXAMT",txtAmountService.Text),      
                                          new SqlParameter("@EDUCESS1AMT",txtPECess.Text),     
                                          new SqlParameter("@EDUCESS2AMT",txtHECess.Text)                                          
                                    };
                            DU.executeprocedure("USP_IVC_SaveDebitNoteServiceDetails", sparam);
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    private void _SaveDebitNote_Total(string strDebitNoteId)
    {
        try
        {
            if (strDebitNoteId != string.Empty)
            {
                SqlParameter[] sparam = 
                                {
                                    new SqlParameter("@DEBITNOTEID",strDebitNoteId),   
                                    new SqlParameter("@TAXABLEAMT",txtTaxable.Text),      
                                    new SqlParameter("@NONTAXABLEAMT",txtNonTaxable.Text),      
                                    new SqlParameter("@SERVICETAXRATE",hidServiceTaxRate.Value),      
                                    new SqlParameter("@SERVICETAXAMT",txtServiceTax.Text),      
                                    new SqlParameter("@EDUCESS1RATE",hidPECessRate.Value),      
                                    new SqlParameter("@EDUCESS1AMT",txtPECess.Text),      
                                    new SqlParameter("@EDUCESS2RATE",hidHECessRate.Value),       
                                    new SqlParameter("@EDUCESS2AMT",txtHECess.Text),      
                                    new SqlParameter("@TOTAL",txtTotalAmount.Text)
                                };
                DU.executeprocedure("USP_IVC_SaveDebitNoteTotals", sparam);
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    #endregion
}
